import Vue from 'vue'
import Vuex from 'vuex'

const toObj = (data, key) => {
	let obj = {};
	data.forEach(v => {
		obj[v[key]] = v;
	});
	return obj;
};

Vue.use(Vuex) // vue的插件机制

let _userInfo = uni.getStorageSync('userInfo') || null;
let _token = uni.getStorageSync('token') || '';
let _sessionInfo = uni.getStorageSync('sessionInfo') || {};
let _phoneInfo = uni.getStorageSync('phoneInfo') || {};


// Vuex.Store 构造器选项
const store = new Vuex.Store({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		$userInfo: _userInfo, // 用户信息
		$token: _token,
		$sessionInfo:_sessionInfo,
		$phoneInfo:_phoneInfo
	},
	mutations: {
		set_userInfo(state, data) {
			state.$userInfo = data;
			uni.setStorageSync('userInfo', data)
		},
		set_sessionInfo(state, data){
			state.$sessionInfo = data;
			uni.setStorageSync('sessionInfo', data)
		},
		set_phoneInfo(state, data){
			console.log(data);
			state.$phoneInfo = data;
			uni.setStorageSync('phoneInfo', data)
		}
	},
	getters: {
		get_userInfo(state) {
			let userInfo = state.$userInfo;
			return userInfo
		},
		get_userInfo(state) {
			let userInfo = state.$userInfo;
			return userInfo
		},
		get_phoneInfo(state) {
			let phoneInfo = state.$phoneInfo;
			return phoneInfo
		},
		get_sessionInfo(state){
			let sessionInfo = state.$sessionInfo;
			return sessionInfo
		},
		get_isLogin(state) {
			let phoneInfo = state.$phoneInfo;
			// return true;
			return !!(phoneInfo.phoneNumber)
		},
	},
	actions: {
		modal(state, content) {
			let params = {
				title: '提示',
				content: '',
				confirmColor: '#00BF9B',
				showCancel: true
			};
			if (typeof content == 'string') {
				params.content = content;
			}
			if (typeof content == 'object') {
				Object.assign(params, content);
			}

			return new Promise((resolve, reject) => {
				uni.showModal({
					...params,
					success: function(res) {
						if (res.confirm) {
							resolve();
						} else if (res.cancel) {
							reject()
						}
					}
				});
			})
		},
		logout(state) {
			this.commit('set_userInfo', null);
			this.commit('set_token', null);
			this.commit('set_role', null);
		}
	}
})

export default store